import 'package:flutter/material.dart';

final GlobalKey<_OverlayBuildFinderState> _keyFinder = GlobalKey(debugLabel: 'overlay_support');

/// 静态app容器
class OverlayBuild extends StatelessWidget {
  OverlayBuild({this.child});
  final Widget child;
  @override
  Widget build(BuildContext context) {
    return OverlayBuildFinder(child: child, key: _keyFinder);
  }
}

class OverlayBuildFinder extends StatefulWidget {
  final Widget child;
  OverlayBuildFinder({Key key, this.child}) : super(key: key);
  @override
  _OverlayBuildFinderState createState() => _OverlayBuildFinderState();
}

class _OverlayBuildFinderState extends State<OverlayBuildFinder> {
  @override
  Widget build(BuildContext context) {
    return widget.child;
  }
}

OverlayState get appOverlayState {
  final context = _keyFinder.currentContext;
  if (context == null) return null;

  NavigatorState navigator;
  void visitor(Element element) {
    if (navigator != null) return;

    if (element.widget is Navigator) {
      navigator = (element as StatefulElement).state;
    } else {
      element.visitChildElements(visitor);
    }
  }

  context.visitChildElements(visitor);

  return navigator.overlay;
}
